package durak.client.view;


import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.net.URL;

import javax.swing.ImageIcon;

public class ImageUtils {
	
	public static Image getImage(String name) {
		if (name == null || name.isEmpty()) {
			return null;
		}

		URL imageURL = ImageUtils.class.getResource("/durak/resources/images/"+name);
		if (imageURL == null) {
			return null;
		}

		return Toolkit.getDefaultToolkit().createImage(imageURL);
	}

	public static ImageIcon getImageIcon(String name) {
		Image image = getImage(name);
		if (image == null) {
			return null;
		}
		return new ImageIcon(image);
	}
	
	public static ImageIcon getImageIconScaled(String name, int width, int height) {
		Image image = getImage(name).getScaledInstance(width, height, Image.SCALE_SMOOTH);
		if (image == null) {
			return null;
		}
		return new ImageIcon(image);
	}
	
	public static ImageIcon getImageIconScaledRotated(String name, int width, int height, int angle) {
		Image image = getImage(name).getScaledInstance(width, height, Image.SCALE_SMOOTH);
		BufferedImage bufferedImage  = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = bufferedImage.createGraphics();
		double x = (height - width)/2.0;
		double y = (width - height)/2.0;
		AffineTransform at = AffineTransform.getTranslateInstance(x, y);
		ImageObserver obs = new ImageObserver() {
			
			@Override
			public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
				// TODO Auto-generated method stub
				return false;
			}
		};
		at.rotate(Math.toRadians(angle), width/2.0, height/2.0);
		g2.drawImage(new ImageIcon(image).getImage(), at, obs);
		g2.dispose();
		
		if (image == null) {
			return null;
		}
		return new ImageIcon(bufferedImage);
	}
}